<template>
    <div class="">
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item><i class="el-icon-message"></i>&nbsp;编辑设备评测</el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        
        <div class="container">
            <el-form ref="form" label-width="120px">
                <el-form-item label="评测封面图：">
                    <div class="sola-upload clearfix">
                        <div class="sola-left clearfix" v-show="headImg!=''">
                            <div  class="sola-flex" >
                                <img  :src="headImg" />
                                <span class="delete" @click="delPicture()"><i class="el-alert__icon el-icon-error"></i></span>
                            </div>
                        </div>
                        <div class="sola-file-box">
                            <el-button type="primary" plain>上传图片<i class="el-icon-upload el-icon--right"></i></el-button>
                            <input class="btn-file" type="file" @change="uploadBanner" v-loading.fullscreen.lock="fullscreenLoading"/>
                            <span style="color:red;padding-left:10px;">建议上传的轮播图比例是4：3 示例200X150 </span>
                        </div>
                    </div>
                </el-form-item>
                
                <el-form-item label="评测标题：">
                    <el-input v-model="title" placeholder="请输入展会标题" style="width:400px"></el-input>
                </el-form-item>
                <el-form-item label="详情内容：">
                    <div class="news-editor">
                        <!-- <editor ref="vueWangeditor" @load="editorLoad" @change="editorChange"
                                :width="editor_style.width" :height="editor_style.height"
                                :useQiniu="true" 
                                id="editor"></editor> -->

                            <ueditor ref="vueWangeditor" @load="editorLoad" @change="editorChange"
                                :width="editor_style.width" :height="editor_style.height"
                                id="editor">
                        </ueditor>
                    </div>
                </el-form-item>
                <el-form-item label="来源：">
                    <el-input v-model="source" placeholder="请输入来源" style="width:400px"></el-input>
                </el-form-item>
                <el-form-item label="授权：">
                    <el-radio-group v-model="authorize" size="small">
                        <el-radio label="本文已获授权" border>本文已获授权</el-radio>
                        <el-radio label="原创" border>原创</el-radio>
                        <el-radio label="印刷搜搜" border>印刷搜搜</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="关键词：">
                    <div class="clearfix">
                        <div v-for="(item,index) in skuProp" style="padding-bottom:10px;" :key="index">
                            <el-input v-model="item.spec"  placeholder="请输入关键词" style="width:150px" clearable></el-input>
                            <el-button type="danger" icon="el-icon-delete" @click="delGoodsSku(item,index)"></el-button>
                        </div>
                        <div style="padding-top:5px;">
                            <el-button type="primary" plain @click="addGoodsSku"><i class="el-icon-plus"></i>&nbsp;&nbsp;新增关键词</el-button>
                        </div>
                    </div>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submit">确认发布</el-button>
                </el-form-item>
            </el-form>
        </div>
        
        <!-- 删除提示框 -->
        <el-dialog title="提示" :visible.sync="delVisible" width="300px" center>
            <div class="del-dialog-cnt">删除不可恢复，是否确定删除？</div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="delVisible = false">取 消</el-button>
                <el-button type="primary" @click="deleteRow">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
import {postUploadBase64,getQiniuUptoken} from '@/api/public';
import {deviceEvaluateQuery,deviceEvaluateEdit} from '@/api/device';
import editor from '../../../components/common/editor.vue'
import ueditor from '../../../components/common/ueditor.vue'
export default {
    name:"deviceEvaluateEdit",
    data() {
        return {
            typeId:'', //当前要删除图片的类型   1封面图 2详情图  3关键词
            idx:0,//当前记录的下标
            delVisible:false,
            fullscreenLoading:false,
            delVisible:false,
            accept: 'image/gif, image/jpeg, image/png, image/jpg', //图片上传类型
            title:'',//学院名称
            headImg:'',  //封面图
            content: '',//正文
            authorize:'原创',//授权
            source:'',//来源
            keywords:[],//关键词数组
            skuProp:[{spec:''}],// 用于关键词
            editorOption: {
                placeholder: '请输入详情内容'
            },
            editorContent:'',

            editor_style: {
                width: 'auto',
                height: 'auto'
            },
            uploadImgUrl: '',
            uploadHeaders: {
                token: ''
            },
            uploadParams: {
                task_id: 0
            },
            needdata:'',//遍历需要数据
            
        }
    },
    components: {
        editor,
        ueditor
    },
    //实例创建
    created(){
        // editor.create()
        if(this.$route.query.id &&this.$route.query.id!=""){
            this.id = this.$route.query.id;
            this.getDetails();
        }
    },
    //计算属性
    computed:{

    },
    //方法
    methods: {
    	//查询详情
    	getDetails(){
    		var param = {
				title:"",
				timeType:0,
				pageIndex:1,
				pageSize:999
        	}
        	deviceEvaluateQuery(param).then((response) => {
                if(response.code==200){
                    var data = response.data.list;//当前返回的数据
                    var id = this.id;
                    var needdata ='';
					$.each(data, function(index,val) {
						if(val.id == id){
							needdata = val
						}
					});	
					this.needdata = needdata;
					this.title = needdata.title;
					this.headImg = needdata.head_img;
					this.authorize = needdata.authorize;
					this.source = needdata.source;
					var keywords=JSON.parse(needdata.keywords);
                    var array =[];
                    keywords.forEach(item=>{
                        var  obj ={};
                        obj.spec = item;
                        array.push(obj);
                    });
                    this.skuProp = array;
                    let content = needdata.content;
                    this.$refs.vueWangeditor.setHtml(content);
                }else{
                    this.$notify.error({
                        title: '异常',
                        offset: 100,
                        message: response.msg
                    });
                }
        	})
    	},
        //确定删除图片
        deleteRow(){
            debugger
            if(this.typeId==1){
                //封面图
                this.headImg="";
            }else if(this.typeId==2){
                
            }else if(this.typeId==3){
                //删除关键词信息
                this.skuProp.splice(this.idx,1);
            }
            
            this.$message.success('删除成功');
            this.delVisible = false;                                                    
        },
        //删除封面提图片
        delPicture(){
            //当前记录的下标
            this.delVisible = true;
        },
        //触发封面图 file
        uploadBanner(event){
            var _event = event;
            var _this = this;
            let reader =new FileReader();
            let img1=event.target.files[0];
            let type=img1.type;//文件的类型，判断是否是图片
            let size=img1.size;//文件的大小，判断图片的大小
            const files = event.target;
            if(this.accept.indexOf(type) == -1){
                this.$message({
                    message: '请选择gif,jpeg,png,jpg格式图片上传',
                    type: 'warning'
                });
                return false;
            }
            else if(size>3145728){
                this.$message({
                    message: '请选择3M以内的图片上传',
                    type: 'warning'
                });
                return false;
            }else if (typeof(FileReader) === 'undefined') {
                this.$notify.error({
                    title: '错误',
                    message: '抱歉，你的浏览器不支持 FileReader，请使用现代浏览器操作！'
                });

            }else {
                this.fullscreenLoading = true;
                let reader = new FileReader();
                reader.readAsDataURL(img1);
                reader.onload = function(e) {
                    var base = this.result;
                    // console.log(base);

                    postUploadBase64(base).then(response=>{
                        // console.log(response);
                        if(response.code==200){
                            _this.$message({
                                message: '恭喜你，图片上传成功',
                                type: 'success'
                            });
                            _this.headImg=response.data;

                        }else{
                            _this.$notify.error({
                                title: '上传图片失败',
                                duration:2000,
                                message: '失败原因：'+response.msg
                            });
                        }
                        _this.fullscreenLoading = false;
                    })

                }

            }
        },
        //删除关键词
        delGoodsSku(item,index){
            if(this.skuProp.length<=1){
                this.$notify({title: '警告',message: '关键词至少要填一项',type: 'warning'});
            }else{
                this.idx = index;
                this.typeId = 3;
                this.delVisible = true;
            }
        },
        //新增关键词
        addGoodsSku(){
            var object = {spec:''};
            this.skuProp.push(object);
            
        },
        toptipSkuFlag(){
            var flag = false;
            var reg = /(^[1-9]\d*(\.\d{1,2})?$)|(^0(\.\d{1,2})?$)/;
            var  stockReg= /^\+?[1-9][0-9]*$/;
            this.skuProp.every((item)=>{
                if(item.spec==""){
                    this.$notify.info({title: '提示',message: '请填写关键词'});
                    flag = true;
                    return false;//跳出循环
                }
            });
            return flag;
        },
        //确认发布
        submit(){
// console.log(this.$refs.vueWangeditor.getText().length);
            if(this.headImg==""){
                this.$notify.info({title: '提示',message: '请上传封面图'});
                return false;
            }
            else if(this.title==""){
                this.$notify.info({title: '提示',message: '请填写标题'});
                return false;
            }
            else if(this.$refs.vueWangeditor.getText().length<1){
                this.$notify.info({title: '提示',message: '请填写详情内容'});
                return false;
            }
            else if(this.source==""){
                this.$notify.info({title: '提示',message: '请输入来源'});
                return false;
            }
            else{
                let param ={}
                param.id=this.id;
                param.title=this.title;
                param.headImg=this.headImg;
                param.content=this.$refs.vueWangeditor.getHtml();
                param.authorize=this.authorize;
                param.source=this.source;
                this.keywords = [];
                this.skuProp.forEach(item=>{
                    this.keywords.push(item.spec);
                })
                param.keywords=JSON.stringify(this.keywords);
                // console.log(param)
                //调用提交方法
                this.saveGoods(param);
            }
        },
        //提交信息上传
        saveGoods(param){
            var _this =this;
            deviceEvaluateEdit(param).then(response=>{
                // console.log(response);
                if(response.code==200){
                    this.$message({
                        message: '恭喜你，发布成功',
                        type: 'success'
                    });
                    setTimeout(function(){
                         _this.$router.push('/device/evaluate');
                    },1500);

                }else{
                    this.$notify.error({
                        title: '发布失败',
                        duration:2000,
                        message: '失败原因：'+response.msg
                    });
                }

            }).catch(error=>{
                console.log(error);
            });
        },
        editorLoad(originalName, resultText) {
            // resultText 服务器端返回的text
            // originalName 上传文件名
            this.$refs.vueWangeditor.insertImg(resultText)
        },
        editorChange(a) {
//                console.log(a)
        },
    }
}
</script>
<style>
    .news-editor .wangEditor-container .wangEditor-txt{
        height: 300px !important;
    }
</style>
<style lang="stylus" scoped>
    .el-form-item .el-cascader{
        width :400px;
    }
    .el-cascader-menus .el-cascader-menu{
        width :240px
    }
    .sola-upload{
        .sola-left{
            width :100%;
            height :auto;
            .sola-flex{
                float:left
                margin-bottom 20px;
                margin-right:15px;
                position:relative;
                .delete{
                    position:absolute;
                    top:2px;
                    right:13px;
                    color: #f56c6c;
                    display:inline-block;
                    padding:5px 5px;
                    .el-alert__icon{font-size:28px;cursor:pointer}
                }
                img {
                    width:200px;
                    height:150px;
                }
            }
        }
        .sola-file-box{
            position:relative;
            .btn-file{
                position:absolute;
                top:0;
                left:0;
                z-index 1;
                opacity:0;
                width :120px;
                height :40px;
                outline: 0;
                background-color :none;
                cursor:pointer;
            }
        }

    }
</style>


